package com.zz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.common.R;
import com.zz.dto.UserRoleDto;
import com.zz.entity.Role;
import com.zz.entity.User;
import com.zz.mapper.RoleMapper;
import com.zz.mapper.UserMapper;
import com.zz.mapper.UserRoleMapper;
import com.zz.entity.UserRole;
import com.zz.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Validated
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public R<Page> page(int page, int pageSize, @Nullable String userName, @Nullable String roleRealName) {
        log.info("userName:{}, roleRealName:{}",userName, roleRealName);
        log.info("UserRoleController=>>>page方法开始执行！");

        // 构造分页构造器
        Page<UserRole> pageInfo = new Page<>(page, pageSize);
        Page<UserRoleDto> userRoleDtoPage = new Page<>(page, pageSize);

        // 条件过滤器
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();

        // 如果用户名不为空
        if (userName != null){
            // 条件查询器
            LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.like(userName != null, User::getName, userName);
            List<User> userList = userMapper.selectList(userWrapper);
            List<Integer> userIds = new ArrayList<>();
            // 遍历所有用户
            for (User user : userList) {
                userIds.add(user.getId());
            }
            if (userIds.isEmpty()){
                return R.error("查询的用户不存在！");
            }
            wrapper.in(UserRole::getUserId, userIds);
        }

        // 如果角色显示名不为空
        if (roleRealName != null){
            // 条件查询器
            LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.like(roleRealName != null, Role::getRealname, roleRealName);
            List<Role> roleList = roleMapper.selectList(roleWrapper);
            log.info("roleList=>{}",roleList);
            ArrayList<Integer> roleIds = new ArrayList<>();

            // 遍历所有角色
            for (Role role : roleList) {
                roleIds.add(role.getId());
            }
            if (roleIds.isEmpty()){
                return R.error("查询的角色不存在！");
            }
            wrapper.in(UserRole::getRoleId, roleIds);
        }

        // 执行分页查询
        // 在page方法内部会将查好的数据封装，赋好值给pageInfo
        userRoleMapper.selectPage(pageInfo, wrapper);

        // 对象拷贝(除了records,records其实就是页面中一整行一整行数据)
        BeanUtils.copyProperties(pageInfo,userRoleDtoPage,"records");

        List<UserRole> records = pageInfo.getRecords();
        log.info("records=>>>{}",records);
        // 遍历list集合对象,item即为获取到的一个个userRole对象
        // log.info("page方法开始遍历List");
        List<UserRoleDto> list = records.stream().map((item) -> {
            UserRoleDto userRoleDto = new UserRoleDto();
            // 将其userRole中的数据复制给UserRoleDto
            BeanUtils.copyProperties(item, userRoleDto);

            int userId = item.getUserId();
            int roleId = item.getRoleId();
            // log.info("userId=>{},roleId=>{}",userId,roleId);

            // 根据id查询分类对象
            User user = userMapper.selectById(userId);
            // log.info("user=>>{}",user.toString());
            Role role = roleMapper.selectById(roleId);
            // log.info("role=>>{}",role.toString());

            if(user != null){
                userRoleDto.setUserName(user.getName());
            }

            userRoleDto.setRoleName(role.getName());
            userRoleDto.setRoleDesc(role.getDescription());
            userRoleDto.setRoleRealName(role.getRealname());

            return userRoleDto;

        }).collect(Collectors.toList());// 把以上创建的dto对象都收集起来

        userRoleDtoPage.setRecords(list);

        return R.success(userRoleDtoPage);
    }


    @Override
    public R<String> deleteUserRole(UserRole userRole) {
        log.info(userRole.toString());
        // 条件过滤器
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        // 过滤条件
        wrapper.eq(UserRole::getRoleId, userRole.getRoleId());
        wrapper.eq(UserRole::getUserId, userRole.getUserId());

        // 从数据库中删除用户角色
        userRoleMapper.delete(wrapper);

        return R.success("成功删除用户角色");
    }


    @Override
    public R<String> addUserRole(UserRole userRole) {
        // 条件过滤器
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        // 过滤条件
        wrapper.eq(UserRole::getUserId, userRole.getUserId());
        wrapper.eq(UserRole::getRoleId, userRole.getRoleId());

        // 查询数据库是否已经存在此用户角色
        UserRole one = userRoleMapper.selectOne(wrapper);

        if (one != null){
            return R.error("此用户角色已存在！");
        }

        // 条件过滤器
        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        // 过滤条件
        wrapper1.eq(User::getId,userRole.getUserId());

        // 判断数据库是否存在此用户
        User user = userMapper.selectOne(wrapper1);

        if(user == null){
            return R.error("此用户不存在！");
        }

        // 向数据库添加数据
        userRoleMapper.insert(userRole);

        return R.success("添加用户角色成功！");
    }


    @Override
    public R<String> updateUserRole(UserRole userRole) {
        // 条件查询
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        // 判断此用户角色是否存在
        wrapper.eq(UserRole::getId, userRole.getId());
        UserRole one1 = userRoleMapper.selectOne(wrapper);
        if(one1 == null){
            return R.error("此用户角色不存在，无法修改！");
        }
        // 判断是否重复
        wrapper.eq(UserRole::getUserId,userRole.getUserId()).eq(UserRole::getRoleId, userRole.getRoleId());
        UserRole one2 = userRoleMapper.selectOne(wrapper);
        if(one2 != null){
            return R.error("该用户角色已经存在，修改失败！");
        }

        userRoleMapper.updateById(userRole);
        return R.success("修改成功！");
    }
}
